//
//  BKResultOfMatchingScoreViewController.m
//  baokaodaxue
//
//  Created by dangyangyang on 15/5/30.
//  Copyright (c) 2015年 宏图教育. All rights reserved.
//

#import "BKResultOfMatchingScoreViewController.h"
#import "BKMathingScoreDataSource.h"
#import "BKSegmentTextField.h"
#import <ReactiveCocoa.h>
#import <RACEXTScope.h>
#import "BKMatchingScoreViewModel.h"
#import "BKCompareViewController.h"
#import "BKColleageViewController.h"
#import <MBProgressHUD.h>

@interface BKResultOfMatchingScoreViewController ()<UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet BKSegmentTextField *dqTextField;
@property (nonatomic ,strong)MBProgressHUD *hud;
@property (weak, nonatomic) IBOutlet BKSegmentTextField *typeTextField;
@property (strong ,nonatomic) BKMatchingScoreViewModel *viewModel;
@property (nonatomic ,strong) NSMutableArray *selectedArray;
@property (nonatomic ,assign) BOOL isCompare;
@property (weak, nonatomic) IBOutlet UIButton *compareButton;

@end

@implementation BKResultOfMatchingScoreViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _selectedArray = [NSMutableArray array];

        _isCompare = NO;
        _dataSource = [[BKMathingScoreDataSource alloc] init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _viewModel
    = [[BKMatchingScoreViewModel alloc] init];
    
    _hud = [[MBProgressHUD alloc] initWithView:self.tableView];
    [self.view addSubview:_hud];
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.labelText = @"正在加载";

    [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BKMatchingScoreTableViewCell class]) bundle:nil] forCellReuseIdentifier:reuserIdentify];
    
    
    _tableView.separatorColor= [UIColor clearColor];
    _tableView.dataSource = _dataSource;
    _tableView.delegate = self;
    
    @weakify(self);
    [RACObserve(self.dqTextField,text) subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSString class]]&&[x length]>0) {
                       [self.hud show:YES];
            
            [self.viewModel colleageWithkq:self.params[@"kq"] kf:self.params[@"kf"] pwh:@"" pwe:@"" wl:@"" pc:@"" dp:self.dqTextField.text fw:self.typeTextField.text currentPage:@"1" success:^(NSArray *dataArray) {
                dispatch_queue_t mainQueue = dispatch_get_main_queue();
                dispatch_async(mainQueue, ^(void) {
                    [self.hud hide:YES];
                    self.dataSource.dataArray = dataArray;
                    [self.dataSource.selectedArray removeAllObjects];
                    [self.tableView reloadData];
                });

                
            } failure:^(NSString *message) {
                dispatch_queue_t mainQueue = dispatch_get_main_queue();
                dispatch_async(mainQueue, ^(void) {
                    [self.hud hide:YES];
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                    [alertView show];
                });
                
            }];
        }
    }];
    
//    [RACObserve(self.piciTextField,text) subscribeNext:^(id x) {
//        @strongify(self);
//        if ([x length]>0) {
//            
//            MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
//            [self.view addSubview:hud];
//            hud.mode = MBProgressHUDModeIndeterminate;
//            hud.labelText = @"正在加载";
//            [hud show:YES];
//            [self.viewModel colleageWithkq:self.params[@"kq"] kf:self.params[@"kf"] pwh:@"" pwe:@"" wl:@"" pc:self.piciTextField.text dp:self.dqTextField.text fw:self.typeTextField.text currentPage:@"1" success:^(NSArray *dataArray) {
//                dispatch_queue_t mainQueue = dispatch_get_main_queue();
//                dispatch_async(mainQueue, ^(void) {
//                    [hud hide:YES];
//                    [self.dataSource.selectedArray removeAllObjects];
//                    self.dataSource.dataArray = dataArray;
//                    [self.tableView reloadData];
//                });
//                
//                
//            } failure:^(NSString *message) {
//                dispatch_queue_t mainQueue = dispatch_get_main_queue();
//                dispatch_async(mainQueue, ^(void) {
//                    
//                    [hud hide:YES];
//                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
//                    [alertView show];
//                });
//                
//            }];
//        }
//    }];

    [RACObserve(self.typeTextField,text) subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSString class]]&&[x length]>0) {
            
            
            [self.hud show:YES];
            [self.viewModel colleageWithkq:self.params[@"kq"] kf:self.params[@"kf"] pwh:@"" pwe:@"" wl:@"" pc:@"" dp:self.dqTextField.text fw:self.typeTextField.text currentPage:@"1" success:^(NSArray *dataArray) {
                dispatch_queue_t mainQueue = dispatch_get_main_queue();
                dispatch_async(mainQueue, ^(void) {
                    [self.hud hide:YES];
                    [self.dataSource.selectedArray removeAllObjects];
                    self.dataSource.dataArray = dataArray;
                    [self.tableView reloadData];
                });
                
                
            } failure:^(NSString *message) {
                dispatch_queue_t mainQueue = dispatch_get_main_queue();
                dispatch_async(mainQueue, ^(void) {
                    [self.hud hide:YES];
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                    [alertView show];
                });
                
            }];
        }
    }];

    
}

- (void)setDataSource:(BKMathingScoreDataSource *)dataSource{

    _dataSource = dataSource;
    __weak BKResultOfMatchingScoreViewController *weakSelf = self;
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(mainQueue, ^(void) {
        [weakSelf.tableView reloadData];
    });
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)p_back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];

}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    
    
    if (_dataSource.isComparing == YES) {
         __weak BKResultOfMatchingScoreViewController *weakSelf = self;
        __block BOOL isHas = NO;
        [_dataSource.selectedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if ([obj[@"cid"] isEqualToString:_dataSource.dataArray[indexPath.row][@"cid"]]) {
                *stop = YES;
                isHas = YES;
                [weakSelf.dataSource.selectedArray removeObject:obj];
            }
        }];
        
        if ([_dataSource.selectedArray count]==2) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"只能选择两所学校" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
            [alertView show];
            return;
        }
        
        if (!isHas) {
            [_dataSource.selectedArray addObject:@{@"cid":_dataSource.dataArray[indexPath.row][@"cid"]}];
            
        }
        
        [tableView reloadData];
        [self performSelectorOnMainThread:@selector(compare) withObject:nil waitUntilDone:YES];
    }else{
        
        
        BKColleageViewController *colleage = [[BKColleageViewController alloc] initWithNibName:NSStringFromClass([BKColleageViewController class]) bundle:nil];
        colleage.name= _dataSource.dataArray[indexPath.row][@"name"];
        colleage.cid = _dataSource.dataArray[indexPath.row][@"cid"];
        
        [self presentViewController:colleage animated:YES completion:nil];
    
    
        
    }

   
    
    
    
    
}
- (IBAction)p_compare:(id)sender {
    
    if (_dataSource.isComparing  == YES) {
        _dataSource.isComparing = NO;
        [_dataSource.selectedArray removeAllObjects];
        [_compareButton setTitle:@"比较" forState:UIControlStateNormal];
        
       
    }else{
    
        _dataSource.isComparing = YES;
        [_dataSource.selectedArray removeAllObjects];
        [_compareButton setTitle:@"取消" forState:UIControlStateNormal];
        
    
    }
   

    [_tableView reloadData];
    

}

- (void)compare{

    if ([_dataSource.selectedArray count]!=2)
        return;
    
    [BKMatchingScoreViewModel compareCol:[NSString stringWithFormat:@"%@,%@",_dataSource.selectedArray[0][@"cid"],_dataSource.selectedArray[1][@"cid"]] success:^(NSArray *dataArray) {
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            dispatch_async(mainQueue, ^(void) {
                BKCompareViewController *compare = [[BKCompareViewController alloc] initWithNibName:NSStringFromClass([BKCompareViewController class]) bundle:nil];
                compare.dataArray = dataArray;
                [self presentViewController:compare animated:YES completion:nil];
            });
    
    
    
        } failure:^(NSString *message) {
            dispatch_queue_t mainQueue = dispatch_get_main_queue();
            dispatch_async(mainQueue, ^(void) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                [alertView show];});
            
    
        
        }];
    

}
@end
